package service;

import dao.CategoryMapper;
import entity.Category;
import entity.CategoryExample;
import httpcode.HttpStatusCodeEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import vo.ResultVO;

import java.util.ArrayList;
import java.util.List;

/**
 * 类目服务
 * Created by weijianyu on 2017/4/24.
 */
@Service
public class CategoryService {

    private static final Logger logger = LogManager.getLogger(CategoryService.class);

    private final CategoryMapper categoryMapper;

    /**
     * 构造方法
     * 初始化
     *
     * @param categoryMapper 类目服务
     */
    @Autowired
    public CategoryService(CategoryMapper categoryMapper) {
        Assert.notNull(categoryMapper, "categoryMapper must not null");
        this.categoryMapper = categoryMapper;
    }

    /**
     * 查询类目信息
     *
     * @return 类目全部信息
     */
    public ResultVO<List<Category>> categoryList() {
        ResultVO<List<Category>> result = new ResultVO<List<Category>>();
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.or().getAllCriteria();
        List<Category> categorys = categoryMapper.selectByExample(categoryExample);
        if (categorys.isEmpty()) {
            logger.warn("数据库无值");
        }

        result.setCode(HttpStatusCodeEnum.SUCCESS.getCode());
        result.setData(categorys);
        result.setErrorMessage("");
        return result;
    }


    /**
     * 获取分类
     *
     * @return 分类信息
     */
    public ResultVO<List<Category>> parentCategorys() {
        ResultVO<List<Category>> result = new ResultVO<List<Category>>();
        CategoryExample categoryExample = new CategoryExample();
        short parent = -1;
        categoryExample.or().andParentEqualTo(parent);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        if (categories.isEmpty()) {
            logger.warn("顶层类目为空");
        }

        result.setCode(HttpStatusCodeEnum.SUCCESS.getCode());
        result.setData(categories);
        result.setErrorMessage("");
        return result;
    }


    /**
     * 获取子类
     *
     * @param id 父类id
     * @return 子类集合
     */
    public List<Short> son(int id) {
        List<Short> ids = new ArrayList<Short>();
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.or().andParentEqualTo((short) id);
        List<Category> categorys = categoryMapper.selectByExample(categoryExample);
        if (categorys.isEmpty()) {
            logger.info("id {id} 查询为空", id);
        } else {
            for (Category category : categorys) {
                ids.add((short) category.getId().intValue());
            }
        }

        return ids;
    }

}
